package com.idea.relax.boot.security.sql;

import org.apache.commons.lang.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * sql过滤
 * @author salad
 */
public class SqlFilter {

	//过滤掉的sql关键字，特殊字符前面需要加\\进行转义
	private static final Pattern PATTERN = Pattern.compile("select|update|and|or|delete|insert|truncate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute|table|"+
		"char|declare|sitename|xp_cmdshell|like|from|grant|use|group_concat|column_name|" +
		"information_schema.columns|table_schema|union|where|order|by|" +
		"'\\*|\\;|\\-|\\--|\\+|\\,|\\//|\\/|\\%|\\#");

	/**
	 * SQL注入过滤
	 *
	 * @param str 待验证的字符串
	 */
	public String sqlInject(String str) {
		if (StringUtils.isBlank(str)) {
			return null;
		}
		// 去掉'|"|;|\字符
		str = StringUtils.replace(str, "'", "");
		str = StringUtils.replace(str, "\"", "");
		str = StringUtils.replace(str, ";", "");
		str = StringUtils.replace(str, "\\", "");

		// 非法字符
		String[] illegalKeywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alert", "create", "drop"};

		// 判断是否包含非法字符
		for (String keyword : illegalKeywords) {
			if (str.toLowerCase().equals(keyword)) {
				throw new RuntimeException("包含非法字符");
			}
		}

		return str;
	}

	public boolean sqlValidate(String str){
		Matcher matcher = PATTERN.matcher(str);
		return matcher.find();
	}

	public String sqlReplace(String str){
		StringBuilder stringBuilder = new StringBuilder();
		if (!sqlValidate(str)){
			return str;
		}
		Matcher matcher = PATTERN.matcher(str);
		while (matcher.find()){
			String s = matcher.replaceAll("");
			stringBuilder.append(s);
		}
		return stringBuilder.toString();
	}

}
